/*********************************************************
 * CS 252 Project 6
 * Android VOIP App
 * 
 * RingerServer Class
 * 
 * This class accepts connections from RingerClient
 *********************************************************/

package com.avp;

import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class RingerServer implements Runnable {
	private static int defaultSocket = 9999;
	Activity2 parent;
	int _socket;
	RingerConnection _conn;
	
	//////////////////
	// Constructors //
	//////////////////
	public RingerServer(Activity2 parent) {
		_socket = defaultSocket;
		this.parent=parent;
	}
	
	public RingerServer(int socket) {
		_socket = socket;
	}
	
	//////////////
	// Mutators //
	//////////////
	public RingerConnection getConn() {
		return _conn;
	}

	/////////////
	// Methods //
	/////////////
	public void run() {
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		
		//set server socket
		try {
			serverSocket = new ServerSocket(_socket);
		} catch (Exception e) {
			Log.v("RingerServer", "Socket error");
			return;
			
		}
		
		//wait for client connection
		while(_conn==null) {
			Log.v("RingerServer", "running, listening on " + _socket);
			try {
				clientSocket = serverSocket.accept();
				
				Log.v("RingerServer", "accepted a client");
				
				_conn = new RingerConnection(clientSocket,parent);
				new Thread(_conn).start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close()
	{
		
		if (_conn!=null)
		{
		_conn.running=false;
		if (_conn.voice!=null)
		_conn.voice.stopConnection();
		
		_conn=null;
		}
	
	}
}
